AnnieRoot.gscene = AnnieRoot.gscene || {};
AnnieRoot.gscene.Gscene = function () {
    var s = this;
    annie.Sprite.call(s);
    /*_a2x_need_start*/
    s.rope = null;/*_a2x_need_end*/
    annie.initRes(s, "gscene", "Gscene");
    //your code here
    var timer = new annie.Timer(1000),
        count = 20,
        mobileCowTime;
    s.addEventListener(annie.Event.ADD_TO_STAGE, function (e) {
        s.setInitGameDataToStartGame();//游戏初始化数据
    });
    /*事件timer*/
    timer.addEventListener(annie.Event.TIMER, function (e) {
        count++;
        if (s.mobileCowPos[AnnieRoot.gameGlobalData.mobileCowCount] == count) {
            count = 0;
            timer.reset();//重设时间
            if (AnnieRoot.gameGlobalData.mobileCowCount < 3) {
                //手机牛出现
                annie.globalDispatcher.dispatchEvent('addMobileCow');//添加手机牛
            } else {
                timer.reset();//重设时间
            }
        }
    });
    /*检测游戏次数,重设游戏*/
    annie.globalDispatcher.addEventListener('setGameInitDataToStartGame', function (e) {
        s.setInitGameDataToStartGame();
    });
    /*游戏开始*/
    annie.globalDispatcher.addEventListener('gameStart', function (e) {
        AnnieRoot.gameGlobalData.isGameOver = false;
        //游戏初始化，开始
        s.mobileCowPos = s.getMobileCowRandomPosArr();
        timer.start();
        //牛牛开始跑出
        s.startAddCowsToStage(1200);//开始添加牛牛到场景
        //时间初始化
        annie.globalDispatcher.dispatchEvent('resetTimerEvent');
    });
    //接收抛出绳索事件
    annie.globalDispatcher.addEventListener('throwRopeEvent', function (e) {
        if (s.rope.currentFrame != 1) {
            return;
        }
        // 也可用开关的方式去处理
        if (!s.hasEventListener(annie.Event.ENTER_FRAME)) {
            s.addEventListener(annie.Event.ENTER_FRAME, s.enF = function (e) {
                //计算是否套中牛牛头部区域
                s.checkHitTest();
            })
        }
        s.addChild(s.rope);
        s.rope.gotoAndPlay(2);
    });
    //绳子抛出动画播放到最后一帧
    s.rope.addEventListener(annie.Event.END_FRAME, s.endFrame = function (e) {
        s.removeEventListener(annie.Event.ENTER_FRAME, s.enF);//移除enterFrame;
        //是否还有绳索
        if (AnnieRoot.gameGlobalData.initGameData.sum > 0) {
            AnnieRoot.gameGlobalData.isCatching = true;
            annie.globalDispatcher.dispatchEvent('stopTimerEvent');
            annie.globalDispatcher.dispatchEvent('readyTime');//321准备时间
        }
        annie.globalDispatcher.dispatchEvent('updateRopeTimes');//更新绳索次数;
        s.rope.gotoAndStop(1);
    });

    /*321准备提示完毕，用户可以继续点击*/
    annie.globalDispatcher.addEventListener('userAbleToPlayGame', function (e) {
        AnnieRoot.gameGlobalData.isCatching = false;
        annie.globalDispatcher.dispatchEvent('resetTimerEvent');//套不中
    });
    //牛牛对象池回收牛牛
    annie.globalDispatcher.addEventListener('recoveryCowEvent', function (e) {
        var cow = e.data;
        if (!cow) {
            throw new Error('e.data参数不能为空');
        }
        s.cowPool.push(cow);
    });
    //添加手机牛牛
    annie.globalDispatcher.addEventListener('addMobileCow', function (e) {
        var cow = s.getCow(3);//获取手机牛;
        cow.x = 680;
        cow.y = s.cowPosY[Math.floor(Math.random() * 2)];
        s.addChildAt(cow, 10);
        cow.gotoAndStop(1);//初始化
        AnnieRoot.gameGlobalData.mobileCowCount++;
        timer.start();
    });
    /*游戏结束*/
    annie.globalDispatcher.addEventListener('gameOver', function (e) {
        //停止时间倒数
        AnnieRoot.gameGlobalData.isCatching = false;
        AnnieRoot.gameGlobalData.level = 0;//重置游戏等级
        s.limDis = 120;
        annie.globalDispatcher.dispatchEvent('stopTimerEvent');
        timer.reset();
        AnnieRoot.gameGlobalData.mobileCowCount = 0;//重新计数手机牛牛出现次数
        count = 0;
        s.stopAddCowsToStage();
    });
    annie.globalDispatcher.addEventListener('serverErrorToDo', function (e) {
        if (AnnieRoot.gameGlobalData.isCatching = true && s.currCatchCow) {
            var child = s.currCatchCow;
            //套不中
            child.gotoAndStop(3);
            setTimeout(function () {
                child.gotoAndStop(1);
                child.speed = 26;
                child.startMoving();//逃跑了
                annie.globalDispatcher.dispatchEvent('updateRopeTimes');//更新绳索次数;
                //是否还有绳索
                if (AnnieRoot.gameGlobalData.initGameData.sum > 0) {
                    setTimeout(function () {
                        annie.globalDispatcher.dispatchEvent('readyTime');//321准备时间
                    }, 1000);
                } else {
                    annie.globalDispatcher.dispatchEvent('gameOver');
                }
                setTimeout(function () {
                    s.rope.visible = true;
                }, 1000)
            }, 200);
        }
    });
    /*断网情况,如果套住牛，绳子断开*/
    annie.globalDispatcher.addEventListener('offlineToDo', function (e) {
        console.log('offlineTodo');
        if (AnnieRoot.gameGlobalData.isCatching = true && s.currCatchCow) {
            var child = s.currCatchCow;
            //套不中
            child.gotoAndStop(3);
            setTimeout(function () {
                child.gotoAndStop(1);
                child.speed = 26;
                child.startMoving();//逃跑了
                s.currCatchCow = null;
                annie.globalDispatcher.dispatchEvent('updateRopeTimes');//更新绳索次数;
                //是否还有绳索
                if (AnnieRoot.gameGlobalData.initGameData.sum > 0) {
                    setTimeout(function () {
                        annie.globalDispatcher.dispatchEvent('readyTime');//321准备时间
                    }, 1000);
                } else {
                    annie.globalDispatcher.dispatchEvent('gameOver');
                }
                setTimeout(function () {
                    s.rope.visible = true;
                }, 1000)
            }, 200);
        }
    })
};
annie.A2xExtend(AnnieRoot.gscene.Gscene, annie.Sprite);
AnnieRoot.gscene.Gscene.prototype.currCatchCow = null;
AnnieRoot.gscene.Gscene.prototype.limDis = 100;
AnnieRoot.gscene.Gscene.prototype.mobileCowPos = [5, 10, 15];
AnnieRoot.gscene.Gscene.prototype.levelDis = [100, 90, 84, 80, 78, 76, 72];
AnnieRoot.gscene.Gscene.prototype.levelRate = [1200, 1100, 1000, 1000, 1000, 1000];
AnnieRoot.gscene.Gscene.prototype.gTimer = null;
AnnieRoot.gscene.Gscene.prototype.cowPosY = [520, 590];
AnnieRoot.gscene.Gscene.prototype.cowPool = [];//对象池
//获取牛牛
AnnieRoot.gscene.Gscene.prototype.getCow = function (type) {
    var s = this,
        cow;
    var len = s.cowPool.length;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            if (s.cowPool[i].type == type) {
                cow = s.cowPool.splice(i, 1)[0];//从数组里面拿出来
                break;
            } else {
                cow = s.creatCow(type);
            }
        }
        // obstacle = s.obstaclePool.shift();
    } else {
        cow = s.creatCow(type);
    }
    return cow;//返回障碍物类实例
}

/*根据类型创建牛牛*/
AnnieRoot.gscene.Gscene.prototype.creatCow = function (type) {
    var cow;
    if (type == 1) {
        cow =  annie.getDisplay("gcow","NormalCow1");
    } else if (type == 2) {
        cow =  annie.getDisplay("gcow","NormalCow2");
    } else if (type == 3) {
        cow =  annie.getDisplay("gcow","MobileCow");//手机牛牛
    }
    return cow;
};
/*随机生成N只牛牛到场景*/
AnnieRoot.gscene.Gscene.prototype.startAddCowsToStage = function (rate) {
    var s = this;
    if (!s.gTimer) {
        s.gTimer = new annie.Timer(rate);
        s.gTimer.addEventListener(annie.Event.TIMER, s.Tim = function (e) {
            var s = this;
            var cow = s.getCow(Math.floor(Math.random() * 2) + 1);//随机获取普通牛;
            cow.x = 680;
            cow.y = s.cowPosY[Math.floor(Math.random() * 2)];
            s.addChildAt(cow, 1);
            cow.gotoAndStop(1);//初始化
        }.bind(s))
    }
    s.gTimer.start();
};
/*停止往场景放入牛牛*/
AnnieRoot.gscene.Gscene.prototype.stopAddCowsToStage = function () {
    var s = this;
    if (s.gTimer) {
        s.gTimer.reset();
        s.gTimer.stop();
        s.gTimer.removeEventListener(annie.Event.TIMER, s.Tim);
        s.gTimer = null;
    }
};
/*检测牛头碰撞*/
AnnieRoot.gscene.Gscene.prototype.checkHitTest = function () {
    var s = this,
        result = null,
        len = s.children.length;
    var ropeHitTestPoint = s.rope.localToGlobal(new annie.Point(s.rope.hitTestArea_mc.x, s.rope.hitTestArea_mc.y));
    for (var i = 0; i < len; i++) {
        var child = s.getChildAt(i);
        if (child.name == 'cow') {
            var cowHeadPoint = child.localToGlobal(new annie.Point(child.cowHitTestArea.x, child.cowHitTestArea.y));
            var dis = annie.Point.distance(ropeHitTestPoint.x, ropeHitTestPoint.y, cowHeadPoint.x, cowHeadPoint.y);//两点距离算法
            // console.log('dis:' + dis);
            if (dis < s.limDis) {
                s.currCatchCow = child;//存储当前套住的牛牛
                s.removeEventListener(annie.Event.ENTER_FRAME, s.enF);//移除enterFrame;
                s.rope.visible = false;
                s.rope.gotoAndStop(1);
                result = true;
                //停止时间倒数
                annie.globalDispatcher.dispatchEvent('stopTimerEvent');
                //套中了
                child.stopMoving();
                child.gotoAndStop(2);
                s.addChildAt(child, 10);
                AnnieRoot.gameGlobalData.isCatching = true;
                annie.globalDispatcher.dispatchEvent('changeUiBtnStatus', 2);//通知Ui改变状态
                //TODO 访问后端,判断是否捕获牛牛
                var cowType = child.type > 2 ? 'phone_cow' : 'cow';//牛牛类型
                //TODO 测试时的测试数据，换正式地址时要注释掉
                // result = testData.isCatchCowData; //test
                /**随机套中**/
                var random=Math.random()*10>>0;
                var isSuccess =0;
                if (random>5){
                    console.log("套中",random);
                    isSuccess=1;
                }else {
                    console.log("套不中",random);
                    isSuccess=2;
                }
                var struggleDis = isSuccess == 1 ? 140 : 120;//挣脱距离
                var struggleTime = isSuccess == 1 ? 1.6 : 1;//挣脱事件
                annie.Tween.to(child, struggleTime, {
                    x: (320 - 150),
                    y: child.y + struggleDis, onComplete: function (e) {
                        annie.globalDispatcher.dispatchEvent('changeUiBtnStatus', 1);//通知Ui改变状态
                        //TODO 回收牛牛，捕获牛牛加1
                        if (isSuccess == 1) {
                            AnnieRoot.gameGlobalData.level++;//游戏级别递增
                            if (child.type < 3) {
                                AnnieRoot.gameGlobalData.userCatchedCowSum++;
                            }
                            s.updateHitTestDis(AnnieRoot.gameGlobalData.level);//更新碰撞距离
                            s.updateAddCowsRate(AnnieRoot.gameGlobalData.level);//更新频率
                            // annie.globalDispatcher.dispatchEvent('resetTimerEvent');
                            annie.globalDispatcher.dispatchEvent('updateUserCows', {
                                num: AnnieRoot.gameGlobalData.userCatchedCowSum,
                                type: child.type
                            });//更新用户的牛牛数
                            s.cowPool.push(child);
                            s.removeChild(child);//移除牛牛出舞台
                            s.rope.visible = true;
                            // AnnieRoot.gameGlobalData.isCatching = false;
                            annie.globalDispatcher.dispatchEvent('cheeringEffect');//啦啦队欢呼效果
                            // var successIconEffect = new gscene.SuccessIcon();
                            var successIconEffect = annie.getDisplay("gscene","SuccessIcon");
                            successIconEffect.x = 40;
                            successIconEffect.y = 380;
                            s.addChild(successIconEffect);
                            annie.globalDispatcher.dispatchEvent('updateRopeTimes');//更新绳索次数;
                            if (AnnieRoot.gameGlobalData.initGameData.sum > 0) {
                                setTimeout(function () {
                                    annie.globalDispatcher.dispatchEvent('readyTime');//321准备时间
                                }, 1000);
                            } else {
                                annie.globalDispatcher.dispatchEvent('gameOver');
                            }
                        } else if (isSuccess == 2) {
                            //套不中
                            child.gotoAndStop(3);
                            setTimeout(function () {
                                child.gotoAndStop(1);
                                child.speed = 26;
                                child.startMoving();//逃跑了
                                // annie.globalDispatcher.dispatchEvent('resetTimerEvent');
                                annie.globalDispatcher.dispatchEvent('updateRopeTimes');//更新绳索次数;
                                //是否还有绳索
                                if (AnnieRoot.gameGlobalData.initGameData.sum > 0) {
                                    setTimeout(function () {
                                        annie.globalDispatcher.dispatchEvent('readyTime');//321准备时间
                                    }, 1000);
                                } else {
                                    annie.globalDispatcher.dispatchEvent('gameOver');
                                }
                                setTimeout(function () {
                                    s.rope.visible = true;
                                    // AnnieRoot.gameGlobalData.isCatching = false;
                                }, 1000)
                            }, 200);
                        } else {
                            /*后端报错的情况*/
                            //套不中
                            child.gotoAndStop(3);
                            setTimeout(function () {
                                child.gotoAndStop(1);
                                child.speed = 26;
                                child.startMoving();//逃跑了
                                annie.globalDispatcher.dispatchEvent('updateRopeTimes');//更新绳索次数;
                                //是否还有绳索
                                if (AnnieRoot.gameGlobalData.initGameData.sum > 0) {
                                    setTimeout(function () {
                                        annie.globalDispatcher.dispatchEvent('readyTime');//321准备时间
                                    }, 1000);
                                } else {
                                    annie.globalDispatcher.dispatchEvent('gameOver');
                                }
                                setTimeout(function () {
                                    s.rope.visible = true;
                                    // AnnieRoot.gameGlobalData.isCatching = false;
                                }, 1000)
                            }, 200);
                            console.log('套牛返回数据报错了！')
                            // alert(result.data);
                        }
                    }
                });
                s.addChildAt(child, 2);//套到的牛，最上层
                break;
            }
        }
    }
    return result;
};
AnnieRoot.gscene.Gscene.prototype.updateHitTestDis = function (level) {
    var s = this;
    if (level > 6) {
        level = 6;
    }
    s.limDis = s.levelDis[level];
};
/*更新频率*/
AnnieRoot.gscene.Gscene.prototype.updateAddCowsRate = function (level) {
    var s = this;
    if (level > 5) {
        level = 5;
    }
    //timer间隔
    if (s.gTimer) {
        // console.log(level, s.gTimer.delay);
        s.gTimer.delay = s.levelRate[level];
        s.gTimer.reset();
        s.gTimer.start();
    }
};
AnnieRoot.gscene.Gscene.prototype.setInitGameDataToStartGame = function () {
    var s = this;
    AnnieRoot.gameGlobalData.initGameData={sum:"9",gamesum:"10"};
    annie.globalDispatcher.dispatchEvent('readyToGameStart');//抛发准备开始游戏321倒数
    AnnieRoot.gameGlobalData.userCatchedCowSum = 0;//重新计算用户套的的牛牛数
    annie.globalDispatcher.dispatchEvent('setGameInitRopeTimes', {index:AnnieRoot.gameGlobalData.initGameData.sum});//初始化的绳索数
    annie.globalDispatcher.dispatchEvent('updataUserGameTimes', AnnieRoot.gameGlobalData.initGameData.gamesum);//更新游戏次数
    annie.globalDispatcher.dispatchEvent('setGameTime');//新开一局游戏,时间初始化
};
/*生成手机牛的出现时间*/
AnnieRoot.gscene.Gscene.prototype.getMobileCowRandomPosArr = function () {
    var posData = [[3, 4, 5, 6, 7], [10, 11, 12, 13, 14], [24, 28, 32, 36, 37]];
    var array = [];
    /*前中后出现一个数组*/
    for (var i = 0; i < posData.length; i++) {
        var randomNum = posData[i][Math.floor(Math.random() * 5)];
        array[i] = randomNum;
    }
    return array;

};
